<?php
/**
 * Created by PhpStorm.
 * User: Qch
 * Date: 2017/9/5
 * Time: 20:57
 */

namespace J\Middleware;


use J\Intent;
use J\Message;
use J\Middleware;

class Debugger implements Middleware
{
    public function machine(\Closure $next): \Closure
    {
        /**
         * @param Intent $intent
         * @return bool
         */
        return function ($intent) use ($next) {
            $r = false;
            try {
                $r = $next($intent);
                $content = $intent->value;

                if ($r === false) {
                    $content = [];

                    $intent->getApp()->error(
                        Message::INTENT_NOT_FIND,
                        ['command' => $intent->getPathinfo()]
                    );
                }
            } catch (\Throwable $e) {
                $text = $e->getMessage() . $e->getTraceAsString();
                $content = value_ajax(false, $text);
            }
            //$r = $next($intent);
            // $content = $intent->value;
            $trace = $intent->getApp()->Console()->getTrace();
            // json
            if (is_array($content)) {
                $content['trace']['rows'] = $trace;
                $intent->value = $content;
                return $r;
            }
            // html
//            $template = $intent->getApp()->get('Debugger.template');
//            $output = html(compact('trace'), $template);
//            if (is_string($output)) {
//                // trace调试信息注入
//                $pos = strripos($content, '</body>');
//                if (false !== $pos) {
//                    $content = substr($content, 0, $pos) . $output . substr($content, $pos);
//                } else {
//                    $content = $content . $output;
//                }
//            }
            $intent->value = $content;
            return $r;
        };
    }
}